package com.atsmart.app.utils;

import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
/**
 * TODO 字符串工具类
 */
public class StringUtil {

	/**
	 * @param str
	 * @return true-str为空  false-str不为空
	 * TODO 字符串非空判断
	 */
	public static boolean isEmptyOrNull(String str) {
		return str == null || str.length() == 0 || str.contentEquals("null")
				|| str.trim().equals("");
	}

	/**
	 * @param is
	 * @param os
	 * TODO  字符串复制
	 */
	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}

	/**
	 * @param string str
	 * @param Object... args
	 * @return
	 */
	public static String format(String str, Object... args) {
		if (isEmptyOrNull(str))
			return "";
		if (args.length == 0)
			return str;
		String result = str;
		Pattern p = java.util.regex.Pattern.compile("\\{(\\d+)\\}");
		Matcher m = p.matcher(str);
		while (m.find()) {
			int index = Integer.parseInt(m.group(1));
			if (index < args.length) {
				result = result.replace(m.group(), args[index].toString());
			}
		}
		return result;
	}

	/**
	 * @return "yyyy-MM-dd HH:mm"
	 */
	public static String getReportTime() {
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date = new Date(System.currentTimeMillis());
		return sfd.format(date);
	}
	
	/**
	 * 
	 * @return "yyyy-MM-dd HH:mm:ss"
	 */
	public static String getFullReportTime() {
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date(System.currentTimeMillis());
		return sfd.format(date);
	}
	
	/**
	 * 
	 * @return "yyyy-MM-dd"
	 */
	public static String getFormTime() {
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date(System.currentTimeMillis());
		return sfd.format(date);
	}

	/**
	 * @param string value
	 * @return "yyyy-mm-dd HH:mm"
	 */
	public static String getTaskTime(String value) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date;
		try {
			date = sdf.parse(value);
			return sdf.format(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * 
	 * @param string value
	 * @return "yyyy-MM-dd"
	 */
	public static String getFormTaskTime(String value) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date;
		try {
			date = sdf.parse(value);
			return sdf.format(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * 
	 * @param long mill
	 * @return  "yyyy-MM-dd HH:mm:ss"
	 */
	public static String millToDate(Long mill) {
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date1 = new Date(mill);
		return sfd.format(date1);
	}

	/**
	 * @param String dateString
	 * @return long: 将字符串 "yyyy-MM-dd" 转换为以毫秒时间单位表示
	 */
	public static Long DateTomill(String dateString) {
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = sfd.parse(dateString);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.getTimeInMillis();
	}
	
	/**
	 * @param String dateString
	 * @return long:将字符串 "yyyy-MM-dd HH:mm" 转换为以毫秒时间单位表示
	 */
	public static Long FormDateTomill(String dateString) {
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date = null;
		try {
			date = sfd.parse(dateString);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.getTimeInMillis();
	}
	
	/**
	 * @param dateString
	 * @return 将字符串 "yyyy-MM-dd HH:mm:ss" 转换为以毫秒时间单位表示
	 */
	public static Long FormDateToTime(String dateString) {
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try {
			date = sfd.parse(dateString);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.getTimeInMillis();
	}

	/**
	 * @param dateString 
	 * @return 拆分后的字符串
	 */
	public static String formatDate(String dateString) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date date = sdf.parse(dateString);
			long now = Calendar.getInstance().getTimeInMillis();
			if (date.getTime() - now < 0) {
				return sdf.format(sdf.parse(dateString));
			} else if (DateUtils.isToday(date)) {
				sdf = new SimpleDateFormat("今天HH:mm");
				return sdf.format(date);
			} else if (DateUtils.isWithinDaysFuture(date, 1)) {
				sdf = new SimpleDateFormat("明天HH:mm");
				return sdf.format(date);
			} else if (DateUtils.isWithinDaysFuture(date, 2)) {
				sdf = new SimpleDateFormat("后天HH:mm");
				return sdf.format(date);
			} else {
				sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				return sdf.format(date);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public static boolean isOverDue(String dateString) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return sdf.parse(dateString).getTime() < (new Date().getTime());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static String longToDate(long timestamp) {
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd");
		Date date1 = new Date(timestamp);
		return sfd.format(date1);
	}

	/**
	 * @return current time with format yyyy-MM-dd HH:mm:ss.SSS
	 */
	public static String getCurrentTime() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		Date date = new Date(System.currentTimeMillis());
		return sdf.format(date);
	}

	public static boolean isImageUrl(String imgUrl) {
		if (isEmptyOrNull(imgUrl)) {
			return false;
		}
		String regEx = "([^\\s]+(\\.(?i)(jpg|png|gif))$)";
		Pattern pattern = Pattern.compile(regEx);
		Matcher matcher = pattern.matcher(imgUrl);
		return matcher.matches();
	}

	/**
	 * 截取一段字符的长度(汉、日、韩文字符长度为2),不区分中英文 ,如果数字不正好，则少取一个字符位
	 * 
	 * @param str
	 *            原始字符串
	 * @param srcPos
	 *            开始位置
	 * @param specialCharsLength
	 *            截取长度(汉、日、韩文字符长度为2)
	 * @return
	 */
	public static String substring(String str, int srcPos,
			int specialCharsLength) {
		if (str == null || "".equals(str) || specialCharsLength < 1) {
			return "";
		}
		if (srcPos < 0) {
			srcPos = 0;
		}
		if (specialCharsLength <= 0) {
			return "";
		}
		// 获得字符串的长度
		char[] chars = str.toCharArray();
		if (srcPos > chars.length) {
			return "";
		}

		int strLength = 0;
		for (int i = 0; i < chars.length; i++) {
			strLength += getSpecialCharLength(chars[i]);
		}

		if (strLength < specialCharsLength) {
			return str;
		}
		int charsLength = getCharsLength(chars, specialCharsLength);
		return new StringBuffer()
				.append(new String(chars, srcPos, charsLength)).append("...")
				.toString();
	}

	/**
	 * 获取一段字符的长度，输入长度中汉、日、韩文字符长度为2， 输出长度中所有字符均长度为1
	 * 
	 * @param chars
	 *            一段字符
	 * @param specialCharsLength
	 *            输入长度，汉、日、韩文字符长度为2
	 * @return 输出长度，所有字符均长度为1
	 */
	private static int getCharsLength(char[] chars, int specialCharsLength) {
		int count = 0;
		int normalCharsLength = 0;
		for (int i = 0; i < chars.length; i++) {
			int specialCharLength = getSpecialCharLength(chars[i]);
			if (count <= specialCharsLength - specialCharLength) {
				count += specialCharLength;
				normalCharsLength++;
			} else {
				break;
			}
		}
		return normalCharsLength;
	}

	private static int getSpecialCharLength(char c) {
		if (isLetter(c)) {
			return 1;
		} else {
			return 2;
		}
	}

	public static boolean isLetter(char c) {
		int k = 0x80;
		return c / k == 0 ? true : false;
	}

	public static String getDomain(String url) {
		if (isEmptyOrNull(url))
			return null;
		String domain;
		try {
			int pos = url.indexOf("//");
			domain = url.substring(pos + 2);
			int endpos = domain.indexOf("/");

			if (url.indexOf("http") > -1) {
				domain = "http://" + domain.substring(0, endpos);
			} else {
				domain = "https://" + domain.substring(0, endpos);
			}
		} catch (StringIndexOutOfBoundsException e) {
			return null;
		} catch (Exception e) {
			return null;
		}
		return domain;
	}

	/**
	 * @param phoneNumber
	 * @return 是电话号码-true  不是电话号码-false
	 */
	public static boolean isPhoneNumberValid(String phoneNumber) {
		return Pattern.matches(
				"^[1]([3][0-9]{1}|50|53|55|56|57|59|58|86|87|88|89)[0-9]{8}$",
				phoneNumber);
	}

	/**
	 * @return 应用版本信息：Version + 版本号 + 时间(MMdd)
	 */
	public static String getBuildVersion() {
		SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
		Date date = new Date(System.currentTimeMillis());
		StringBuilder sb = new StringBuilder();
		sb.append("应用版本信息：Version ")
				.append(BizApp.getInstance().getResources()
						.getString(R.string.app_version)).append('.')
				.append(sdf.format(date));
		return sb.toString();
	}
	
	/**
	 * 判断是否为纯数字
	 * @param str
	 * @return true--纯数字  false--不是纯数字
	 */
	public static boolean isNum(String str){
		return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
	}
}
